package com.dream.wukong.common.core.jdbc.sqltemplate.impl;

import com.dream.wukong.common.core.jdbc.sqlconfig.SqlMapper;
import com.dream.wukong.common.core.util.StringUtil;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: wuyichao
 * @Description:
 * @Date: Created in 10:22 2018/9/18.
 * @Modified:
 */
public class VelocitySqlTemplate extends BaseSqlTemplate {

    public String getParsedSql(String sqlKey, Map<String, Object> map) {
        VelocityContext context =  new VelocityContext(new HashMap<String, Object>(map) ) ;
        context.put("StringUtil",  new VelocityStringUtil());
        StringWriter w = new StringWriter();
        SqlMapper sqlMapper = sqlConfig.getSqlMapper(sqlKey);
        if (sqlMapper!=null) {
            try {
                Velocity.evaluate(context, w, this.getClass().getName(), sqlMapper.getSqlCode());
            } catch ( Exception e) {
                throw new IllegalArgumentException("Velocity.evaluate {" + sqlKey + "}   error"+ e.getMessage());
            }
        }else{
            throw new IllegalArgumentException("Velocity  sqlConfig  {" + sqlKey + "} not exist");
        }
        return  w.toString() ;
    }

    public static class VelocityStringUtil {

        public String parseToSqlOr(String srcString, String columnName){
            return StringUtil.parseToSqlOr(srcString, columnName);
        }

    }



}